package com.gethb.prod.service.impl;

import java.sql.Timestamp;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.gethb.data.dao.MessageMapper;
import com.gethb.data.mdo.MessageDo;
import com.gethb.prod.service.ISendMessageService;
import com.gethb.prod.vo.MessageInVo;
import com.gethb.prod.vo.MessageOutVo;
import com.gethb.pub.utils.BaseInVo;
import com.gethb.pub.utils.ShortMessageUtils;
import com.gethb.pub.utils.ToolsUtils;

@Component("sendMessageService")
public class SendMessageServiceImpl implements ISendMessageService {
	
	private static final Logger LOG = LoggerFactory.getLogger(SendMessageServiceImpl.class);
	
	@Resource
	MessageMapper messageMapper;//接口

	@Override
	public String sendMessage(String jsonString) {
		LOG.info("Start发送短信服务开始");
		MessageOutVo outVo = new MessageOutVo();
		MessageInVo inVo = BaseInVo.parseJsonStr(jsonString, MessageInVo.class);
		// 生成短信唯一id
		String messageId = getMessageId();
		LOG.info("短信ID为" + messageId);
		LOG.info("手机号码为" + inVo.getMblphNo());
		
		// 插入数据
		MessageDo messageDo =new MessageDo();
		messageDo.setMessageId(messageId);
		messageDo.setMblphNo(inVo.getMblphNo());
		messageDo.setCode(String.valueOf((int) ((Math.random()*9+1)*100000)));
		messageDo.setNumber("1");
		messageMapper.addNewMessage(messageDo);
		
		// 调用发送短信方法
		SendSmsResponse sendSmsResponse = 
				ShortMessageUtils.requestMessage(messageDo);
		
		// 更新发送短信数据库结果
		messageDo.setBizId(sendSmsResponse.getBizId());
		messageDo.setErrCode(sendSmsResponse.getCode());
		messageDo.setRequestId(sendSmsResponse.getRequestId());
		messageDo.setErrInf(sendSmsResponse.getMessage());
		messageMapper.updateMessageResult(messageDo);
		
		// 返回数据
		outVo.setNumber(messageDo.getNumber());
		outVo.setState(sendSmsResponse.getCode());
		outVo.setMessageId(messageId);
		
		LOG.info("end发送短信服务开始");
		return JSON.toJSONString(outVo);
	}

	/**
	 * 获取短信ID 
	 * @return
	 */
	public String getMessageId() {
		String num;
		MessageDo messageDo =new MessageDo();
		String messageId = messageMapper.findOneDayMaxInf(messageDo);
		if (null == messageId) {
			num = "00000";
		} else {
			num = messageId.substring(17, 22);
		}
		return ToolsUtils.getMessageId(num);
	}

	
}
